<template>
  <div class="box">
    <h3>拖动下方滑块完成拼图</h3>
    <div ref="bgImgref" class="img-box">
      <img class="bg" src="../assets/hycdn.jpeg" alt="" />
      <img
        class="hd"
        src="../assets/hycdn.png"
        :style="{ left: data.left + 'px', top: data.top + 'px' }"
        alt=""
      />
    </div>
    <div class="btn-box">
      <div
        ref="btnref"
        class="btn"
        :style="{ left: data.left + 'px' }"
        @mousedown="btnMouseDown"
        @mouseup="btnMouseUp"
      >
        |||
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, toRefs } from "vue";

let $props = defineProps({
  top: {
    type: Number,
    default: 45,
  },
});

let $emit = defineEmits(["getPosition"]);

const data = reactive({
  left: 28,
  top: $props.top,
  btnleft: 0,
  btnref: null,
  offsetLeft: 0,
  bgImgref: null,
});
const { btnref, bgImgref } = toRefs(data);

onMounted(() => {
  data.offsetLeft = data.bgImgref.offsetLeft;
  console.log("onMounted");
  document.body.addEventListener("mouseup", btnMouseUp);
});

var btnMouseDown = (e) => {
  // console.log(e);
  //计算出鼠标按下位置 pagex-btn距离窗口的位置=鼠标位置距离btn的边距
  data.btnleft = e.pageX - data.btnref.offsetLeft;
  document.body.addEventListener("mousemove", btnMouseMove);
};

//滑动时只要求鼠标不松开
var btnMouseMove = (e) => {
  // console.log("滑动");
  //left=pageX - data.btnref.offsetLeft
  let x = e.pageX - data.offsetLeft - data.btnleft;
  if (x <= 0) x = 0;
  else if (x >= 285) x = 285;
  data.left = x;
};

var btnMouseUp = (e) => {
  //console.log(data.left);
  $emit("getPosition", data.left);
  document.body.removeEventListener("mousemove", btnMouseMove);
};
</script>

<style scoped>
html,
body {
  width: 100%;
  height: 100%;
  user-select: none;
}
.box {
  width: 340px;
  height: 300px;
  border: 1px solid #ccc;
  margin: 0 auto;
  padding: 10px;
}
.img-box {
  position: relative;
}
.bg {
  width: 100%;
}
.hd {
  position: absolute;
  height: 68px;
  width: 68px;
  /* top: 45px; */
  left: 26px;
  cursor: pointer;
}
.btn-box {
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #e4e4e4;
  margin-top: 15px;
}
.btn {
  position: relative;
  top: -10px;
  left: 26px;
  width: 55px;
  height: 30px;
  text-align: center;
  letter-spacing: 5px;
  line-height: 30px;
  color: #fff;
  border-radius: 15px;
  background-color: rgb(26, 121, 255);
  box-shadow: rgb(26 121 255 / 52%) 0px 0px 10px 1px;
  cursor: pointer;
}
</style>
